"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

interface NewEvent {
  title: string
  description: string
  date: string
}

export default function NewEventPage({
  params: { id: libraryId }
}: {
  params: { id: string }
}) {
  const router = useRouter()
  const [event, setEvent] = useState<NewEvent>({
    title: "",
    description: "",
    date: new Date().toISOString().split('T')[0]
  })
  const [error, setError] = useState("")
  const [saving, setSaving] = useState(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setSaving(true)

    try {
      const response = await fetch(`/api/admin/libraries/${libraryId}/events`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(event)
      })

      if (!response.ok) throw new Error("创建失败")
      
      router.push(`/admin/libraries/${libraryId}`)
      router.refresh()
    } catch (err) {
      setError("创建事件失败")
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="max-w-2xl mx-auto p-8">
      <h1 className="text-2xl font-bold mb-6">添加新事件</h1>

      {error && (
        <div className="text-red-500 mb-4">{error}</div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-1">标题</label>
          <Input
            value={event.title}
            onChange={e => setEvent(prev => ({ ...prev, title: e.target.value }))}
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">描述</label>
          <Textarea
            value={event.description}
            onChange={e => setEvent(prev => ({ ...prev, description: e.target.value }))}
            rows={4}
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">日期</label>
          <Input
            type="date"
            value={event.date}
            onChange={e => setEvent(prev => ({ ...prev, date: e.target.value }))}
            required
          />
        </div>

        <div className="flex space-x-4">
          <Button type="submit" disabled={saving}>
            {saving ? "创建中..." : "创建"}
          </Button>
          <Button
            type="button"
            variant="outline"
            onClick={() => router.push(`/admin/libraries/${libraryId}`)}
          >
            取消
          </Button>
        </div>
      </form>
    </div>
  )
} 